package com.tencent.wxcloudrun.controller;

import com.tencent.wxcloudrun.controller.utils.ResultResponse;
import com.tencent.wxcloudrun.config.MinioConfig;
import com.tencent.wxcloudrun.controller.utils.MinioUtil;
import io.minio.messages.Bucket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping(value = "minio")
public class FileController {

    @Autowired
    private MinioUtil minioUtil;
    @Autowired
    private MinioConfig prop;

    @GetMapping("/bucketExists")
    public ResultResponse bucketExists(@RequestParam("bucketName") String bucketName) {
        return ResultResponse.ok(minioUtil.bucketExists(bucketName),"查询成功");
    }

    @GetMapping("/makeBucket")
    public ResultResponse makeBucket(String bucketName) {
        return ResultResponse.ok(minioUtil.makeBucket(bucketName),"创建成功");
    }

    @GetMapping("/removeBucket")
    public ResultResponse removeBucket(String bucketName) {
        return ResultResponse.ok(minioUtil.removeBucket(bucketName),"删除成功");
    }

    @GetMapping("/getAllBuckets")
    public ResultResponse getAllBuckets() {
        List<Bucket> allBuckets = minioUtil.getAllBuckets();
        return ResultResponse.ok(allBuckets,"查询成功");
    }

    @PostMapping("/upload")
    public ResultResponse upload(@RequestParam("file") MultipartFile file) {
        String objectName = minioUtil.upload(file);
        if (null != objectName) {
            return ResultResponse.ok((prop.getEndpoint() + "/" + prop.getBucketName() + "/" + objectName),"上传成功");
        }
        return ResultResponse.error("上传失败");
    }

    @GetMapping("/preview")
    public ResultResponse preview(@RequestParam("fileName") String fileName) {
        return ResultResponse.ok(minioUtil.preview(fileName),"查询成功");
    }

    @GetMapping("/download")
    public ResultResponse download(@RequestParam("fileName") String fileName, HttpServletResponse res) {
        minioUtil.download(fileName,res);
        return ResultResponse.ok(true,"下载成功");
    }

    @PostMapping("/delete")
    public ResultResponse remove(String url) {
        String objName = url.substring(url.lastIndexOf(prop.getBucketName()+"/") + prop.getBucketName().length()+1);
        minioUtil.remove(objName);
        return ResultResponse.ok(objName,"删除成功");
    }

}




